package cn.lingyangwl.agile.dynamic.config.core;

import cn.lingyangwl.agile.dynamic.config.model.ActionTypeEnum;
import cn.lingyangwl.agile.dynamic.config.model.ConfigMsg;
import cn.lingyangwl.agile.dynamic.config.model.RefreshConfigMQ;
import cn.lingyangwl.agile.model.enums.ConfigKeyEnum;
import cn.lingyangwl.agile.model.module.tenant.TenantContext;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Slf4j
@Service
public class DynamicConfigServiceImpl implements DynamicConfigService {
    @Resource
    private RabbitTemplate rabbitTemplate;

    public void publishRouteEvent(ConfigMsg configMsg) {
        try {
            RefreshConfigMQ message = new RefreshConfigMQ();
            message.setTenantId(configMsg.getTenantId());
            message.setMainTenantId(configMsg.getMainTenantId());
            message.setConfigMsg(configMsg);
            rabbitTemplate.convertAndSend(RefreshConfigMQ.EXCHANGE, RefreshConfigMQ.KEY, message.toMessage());
        } catch (Exception e) {
            log.error("bus publish event fail:",e);
            throw new BizException("同步配置失败");
        }
    }

    @Override
    public void publishDeleteConfigEvent(ConfigKeyEnum configKey) {
        if (Objects.isNull(configKey)) {
            return;
        }
        ConfigMsg payload = ConfigMsg.builder().tenantId(TenantContext.get().getTenantId())
                        .configKey(configKey.getKey()).actionType(ActionTypeEnum.DELETE).build();
        publishRouteEvent(payload);
    }

    @Override
    public void publishRefreshConfigEvent(ConfigMsg payload) {
        String tenantId = ObjectUtils.defaultIfNull(payload.getTenantId(), TenantContext.get().getTenantId());
        payload.setTenantId(tenantId);
        payload.setActionType(ActionTypeEnum.UPDATE_OR_SAVE);
        publishRouteEvent(payload);
    }

}